let WebUtil = {
    initHHmmssStr: (timeStamp) => {
        if (!timeStamp) return "";
        if (isNaN(Number(timeStamp))) return timeStamp;
        let s;
        let hours = parseInt((timeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = parseInt((timeStamp % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = (timeStamp % (1000 * 60)) / 1000;
        s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds);
        return s;
    },
    /**
     * 时间戳转日期
     * @param {String} times 时间戳
     * @param {Boolean} boolean 默认 YY-MM-DD
     */
    initTimeStr: (times, type) => {
        if (isNaN(Number(times))) return times;
        if (times != undefined && times != null && times > 0) {
            let date = new Date(Number(times));
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = (date.getDate() < 10 ? '0' + Number(date.getDate()) : date.getDate()) + ' ';
            let h = (date.getHours() < 10 ? '0' + Number(date.getHours()) : date.getHours()) + ':';
            let m = (date.getMinutes() < 10 ? '0' + Number(date.getMinutes()) : date.getMinutes()) + ':';
            let s = (date.getSeconds() < 10 ? '0' + Number(date.getSeconds()) : date.getSeconds());
            if (type == "year") {
                return Y
            }
            if (type == "month") {
                return Y + M
            }
            if (type == "day") {
                return Y + M + D
            }
            if (type == "hours") {
                return Y + M + D + h
            }
            if (type == "min") {
                return Y + M + D + h + m
            } else {
                return Y + M + D + h + m + s;

            }
        } else {
            return '';
        }
    },
    getMonthList: (date, up) => {
        // js 获取当前日期到之后一个月30天的日期区间
        var dateList = [];
        let startDate = new Date(date);
        let endDate = new Date(date);
        if (up) {
            startDate.setDate(endDate.getDate() - 30);
        } else {
            endDate.setDate(startDate.getDate() + 30);
        }
        while ((endDate.getTime() - startDate.getTime()) >= 0) {
            let year = startDate.getFullYear();
            let month = (startDate.getMonth() + 1).toString().length === 1 ? "0" + (startDate.getMonth() + 1).toString() : (
                startDate.getMonth() + 1);
            let day = startDate.getDate().toString().length === 1 ? "0" + startDate.getDate() : startDate.getDate();
            dateList.push(year + "-" + month + "-" + day);
            startDate.setDate(startDate.getDate() + 1);
        }
        return dateList;
    },
    // 获取date是星期几
    getWeek(date) {
        var tempDate = new Date(date);
        var days = tempDate.getDay();
        var week;
        switch (days) {
            case 1:
                week = '一';
                break;
            case 2:
                week = '二';
                break;
            case 3:
                week = '三';
                break;
            case 4:
                week = '四';
                break;
            case 5:
                week = '五';
                break;
            case 6:
                week = '六';
                break;
            case 0:
                week = '日';
                break;
        }
        return week;
    },
    // 判断str是不是今天
    judgeTime(str) {
        var s = new Date(new Date(str).setHours(0, 0, 0, 0)).getTime();
        var e = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
        if (s == e) {
            return true;
        } else {
            return false;
        }
    },
    // 计算两个日期之间的天数
    getDatesBetweenDates(stime, etime) {
        var diffdate = new Array();
        var i = 0;
        //开始日期小于等于结束日期,并循环
        while (stime <= etime) {
            diffdate[i] = stime;

            //获取开始日期时间戳
            var stime_ts = new Date(stime).getTime();
            //增加一天时间戳后的日期
            var next_date = stime_ts + (24 * 60 * 60 * 1000);

            //拼接年月日，这里的月份会返回（0-11），所以要+1
            var next_dates_y = new Date(next_date).getFullYear() + '-';
            var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
            var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();

            stime = next_dates_y + next_dates_m + next_dates_d;

            //增加数组key
            i++;
        }
        return diffdate
    },
    /**
     * //删除左右两端的空格
     * @param {String} str 
     * @returns 
     */
    trim: (str) => {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    },
    /**
     * 数组第一个和第二个替换
     * @param {*} arr 数组
     * @param {*} startIndex 第一个结束索引
     * @param {*} endIndex 第二个结束索引
     * @returns 
     */
    changeArrIndex(arr, startIndex, endIndex) {
        arr[startIndex] = arr.splice(endIndex, 1, arr[startIndex])[0]
        return arr;
    },
    /**
     * file文件流转base64
     * @param {*} blob 
     * @param {*} cb 
     */
    blobToDataURL(blob, cb) {
        let reader = new FileReader();
        reader.onload = function (evt) {
            let base64 = evt.target.result;
            cb(base64);
        };
        reader.readAsDataURL(blob);
    },
    OP(option) {
        if (top.$("#" + option.id).css("display") == "none") { top.$("#" + option.id).remove(); }

        let p = ""
        if (option.params && Object.keys(option.params).length) {
            for (const key in option.params) {
                const item = option.params[key];
                p += "&" + key + "=" + item
            }
            if (option.iframeUrl) {
                if (option.iframeUrl.indexOf("?") != -1) {
                    p = p.replace("&", "");
                } else {
                    p = p.replace("&", "?");
                }
                option.iframeUrl += p;
            }
        }
        top.$("body").append(`<div class="modal inmodal fade" id="${option.id}" tabindex="-1" role="dialog" aria-hidden="true" data-keyboard="true" data-backdrop="${option.backdrop || 'static'}">
                                <div class="modal-dialog modal-lg">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" onclick="WebUtil.CL('${option.id}')"><span
                                                    aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                                            <h4 class="modal-title">${option.title}</h4>
                                        </div>
                                        <iframe src="${option.iframeUrl}" frameborder="0" name="frame - container" id="iframe_${option.id}"
                                        class= "full-width" ></iframe >
                                    </div >
                                </div >
                          </div >
        `)
        top.$("#" + option.id).modal('show')
        top.$("#" + option.id + " iframe")[0].contentWindow.name = option.id;

        if (option.height) {
            top.$("#" + option.id + " iframe").css("height", option.height + 'px')
        } else {
            WebUtil.setIframeHeight(option.id)
        }

    },
    setIframeHeight(iframe_id) {//父页面中iframe的id
        var cacheHeight = 0;
        function run(iframe_id) {
            var mf = top.$("#" + iframe_id + " iframe")[0];
            // when the main frame has already been loaded, the check its height  
            if (mf && mf.contentDocument && mf.contentDocument.body) {
                var iframeHeight = mf.contentDocument.body.clientHeight;
                if (iframeHeight && iframeHeight != cacheHeight) {
                    // cache the main frame height  
                    cacheHeight = iframeHeight;
                    mf.contentDocument.body.style.overflow = "hidden"
                    $(mf).height(iframeHeight);
                }
            }
            setTimeout(run, 50, iframe_id);
        }
        run(iframe_id);
    },
    Refresh(type, id) {
        let iframeName = id ? ("iframe_" + id) : "frame-container";
        eval(`top.$("#${iframeName}")[0].contentWindow.${type}`)
    },
    /**
     * 将数据转成children层级格式
     * @param {*} list  数据源
     * @param {*} id  id
     * @param {*} parentid  父级id
     * 
     * @returns 
     */
    handleLevel(list, id, parentid, Maxlevel = 9999999) {
        let dataArr = [];
        if (list.length > 0) {
            let recursionLevel = function (item, level = 0) {
                item.children = [];
                item.level = level;
                item.iconText = "";
                for (let j = 0; j < level; j++) { item.iconText += "∟"; }
                for (let i = 0; i < list.length; i++) {
                    if (item[id] == list[i][parentid] && Maxlevel > level) {
                        item.children.push(list[i])
                        recursionLevel(list[i], level + 1)
                    }
                }
                if (item[parentid] == 0) { return item; }
            }

            for (let i = 0; i < list.length; i++) {
                if (list[i][parentid] == 0) {
                    dataArr.push(recursionLevel(list[i]))
                }
            }
        }
        return dataArr;
    },
    /**
     * 将数据转成树形表格格式
     * @param {*} list  数据源
     * @param {*} id  id
     * @param {*} parentid  父级id
     * 
     * @returns 
     */
    handleLevel2(list, iid, parentid) {
        let dataArr = [];
        if (list.length == 1) {
            list[0].level = 0;
            list[0].iconText = "";
            return list;
        }
        if (list.length > 0) {
            let recursionLevel = function (list, id, level = 0) {
                for (let i = 0; i < list.length; i++) {
                    const item = list[i];
                    if (item[parentid] == id) {
                        dataArr.push(item);
                        item.level = level;
                        item.iconText = ""
                        for (let j = 0; j < level; j++) { item.iconText += "∟"; }
                        recursionLevel(list, item[iid], level + 1)
                    }
                }
            }
            recursionLevel(list, 0)
        }
        return dataArr
    },
    /**
 * 函数防抖
 * @param {Function} fn callback
 * @param {Number} delay 时间
 * @param {*} immediate 立即执行
 * @returns 
 */
    debounce(fn, delay, immediate) {
        var timer = null;
        immediate = immediate || false;
        return function () {
            var context = this;
            var args = arguments;
            //清除上一次延时器
            timer && clearTimeout(timer);
            // 是否立即执行
            if (immediate) {
                var callbackNow = !timer;
                timer = setTimeout(() => {
                    timer = null;
                }, delay);
                callbackNow && fn.apply(context, args);
            } else {
                timer = setTimeout(() => {
                    fn.apply(context, args);
                }, delay);
            }
        }
    },
    /**
     * 函数节流
     * @param {Function} fn callback
     * @param {Number} delay 时间
     * @returns 
     */
    throttle(fn, delay) {
        var lastTime = Date.now();
        return function () {
            var context = this;
            var args = arguments;
            var curTime = Date.now();
            console.log(curTime - lastTime);
            if (curTime - lastTime >= delay) {
                fn.apply(context, args);
                lastTime = curTime;
            }
        }
    },
    getEvtCurDom(dom) {
        var evt = window.event || arguments[0];
        let startX = (evt.x || evt.clientX);
        let startY = (evt.y || evt.clientY);
        for (let i = 0; i < $(dom).length; i++) {
            const element = $(dom)[i];
            let rect = element.getBoundingClientRect()
            let sl = rect.width + rect.left;
            let st = rect.height + rect.top;
            if (startX > rect.left && startX < sl && startY > rect.top && startY < st) {
                return element;
            }
        }
    },
    arrGrouping(arr, field) {
        let o = {}
        for (let i = 0; i < arr.length; i++) {
            const d = arr[i];
            for (const key in d) {
                if (key == field) {
                    let ob = d[key];
                    if (o[ob]) {
                        o[ob].push(d)
                    } else {
                        o[ob] = [d]
                    }
                }

            }
        }
        return o;
    },
    Selection(option) {
        document.onmousedown = function (e) {
            if ($(e.target).is(option.appointClass)) {
                var isSelect = true;
                var selList = $(option.el);
                var downSelList = [];
                // 获取事件触发后的event对象，做了一个兼容性处理
                var evt = window.event || arguments[0];
                // 存放鼠标点击初始位置
                var startX = (evt.x || evt.clientX);
                var startY = (evt.y || evt.clientY);

                // 创建一个框选元素
                var selDiv = document.createElement("div");
                // 给框选元素添加CSS样式，使用决定定位
                selDiv.style.cssText = "position:absolute; width:0px; height:0px; font-size:0px; margin:0px; padding:0px; border:1px dashed #0099FF; z-index:1000;background:#409eff; filter:alpha(opacity:60); opacity:0; display:none";
                // 添加ID
                selDiv.id = "selectDiv";
                // appendChild()向节点添加最后一个子节点
                $(document.body).append(selDiv)
                // 根据起始位置，添加定位
                selDiv.style.left = startX + "px";
                selDiv.style.top = startY + "px";
                // 根据坐标给选框修改样式
                var _x = null;
                var _y = null;

                function addRoomBook(e) {
                    if (isSelect) {
                        if (selDiv.style.display == "none") {
                            selDiv.style.display = "";
                        }
                        // 获取当前鼠标位置
                        _x = (evt.x || evt.clientX);
                        _y = (evt.y || evt.clientY);
                        if (_x < 0 || _y < 0) {
                            isSelect = false;
                            option.up(e);
                            return;
                        }
                        selDiv.style.left = Math.min(_x, startX) + 'px';
                        selDiv.style.top = Math.min(_y, startY) + 'px';
                        selDiv.style.width = Math.abs(_x - startX) + 'px';  //Math.abs()返回数的绝对值
                        selDiv.style.height = Math.abs(_y - startY) + 'px';
                        // *******************************************************************************
                        // 获取参数
                        var _l = selDiv.offsetLeft;
                        var _t = selDiv.offsetTop;
                        var _w = selDiv.offsetWidth;
                        var _h = selDiv.offsetHeight;
                        for (var i = 0; i < selList.length; i++) {
                            let rect = selList[i].getBoundingClientRect()
                            var sl = rect.width + rect.left;
                            var st = rect.height + rect.top;
                            if (sl > _l && rect.left < _l + _w && rect.top < _t + _h && st > _t) {
                                // 该DOM元素被选中，进行处理
                                if (selList[i].className.indexOf(" selected") == -1) {
                                    $(selList[i]).addClass("selected");
                                    downSelList.push(selList[i])
                                    option.move(selList[i], 1)
                                }
                            } else {
                                if (selList[i].className.indexOf(" selected") != -1) {
                                    for (let j = 0; j < downSelList.length; j++) {
                                        const element = downSelList[j];
                                        if (element == selList[i]) {
                                            $(selList[i]).removeClass("selected");
                                            downSelList.splice(j, 1)
                                            option.move(selList[i], 2)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                addRoomBook(e);
                clearEventBubble(e);
                document.onmousemove = function (e) {
                    evt = window.event || arguments[0];
                    // 移动鼠标时隐藏交叉线
                    _x = (evt.x || evt.clientX);
                    _y = (evt.y || evt.clientY);
                    if ((_y <= 10 || _x <= 10) && isSelect) {
                        isSelect = false;
                        if (selDiv) {
                            $("#selectDiv").remove();
                        }
                        option.up(e);
                        selList = null, _x = null, _y = null, selDiv = null, startX = null, startY = null, evt = null;
                        return;
                    }
                    addRoomBook(e);
                    clearEventBubble(evt);
                }

                if (option.inClass) {
                    $(document).on("mouseenter", option.inClass, function (e) {
                        if (isSelect) {
                            option.in && option.in($(this), e)
                        }
                        clearEventBubble(e);
                    })
                }

                // 放开鼠标，选框消失
                document.onmouseup = function (e) {
                    if (isSelect) { option.up && option.up(e); }
                    isSelect = false;
                    if (selDiv) { $("#selectDiv").remove(); }
                    selList = null, _x = null, _y = null, selDiv = null, startX = null, startY = null, evt = null;
                    clearEventBubble(e);
                    document.onmouseup = null;
                    document.onmousemove = null;
                }
            }
        }
        function clearEventBubble(evt) {
            // stopPropagation()不再派发事件。终止事件在传播过程的捕获、目标处理或起跑阶段进一步传播
            if (evt.stopPropagation)
                evt.stopPropagation();
            else
                evt.cancelBubble = true;  // 阻止该事件的进一步冒泡
            if (evt.preventDefault)
                evt.preventDefault();   // 取消事件的默认动作
            else
                evt.returnValue = false;
        }
    }

}
window.WebUtil = WebUtil;